<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#odiv{
				width: 400px;
				height: 400px;
				position:absolute;
				left: 0px;
				background-color:red ;
				border: 1px solid black;
			}
			.bj{
				padding: 0px;
				position: relative;
				margin: 0 auto;
				border: 1px solid red;
				width: 800px;
				height: 1200px;
				background-color:yellowgreen ;
				
				
			}
		</style>
		<script type="text/javascript">
		
			var odiv;
			window.onload=function(){
			odiv=document.getElementById('odiv');
			var contran =document.getElementById('contran');
			var speed =10;
			var width =contran.clientWidth-odiv.offsetWidth;
			var height =contran.clientHeight-odiv.offsetHeight;
				window.onkeydown=function(ev){
					
					var oEvent=ev || event;
//					if(oEvent.keyCode==37){
//						oEvent.keyCode=-oEvent.keyCode;
//					}
					console.log(oEvent.keyCode);
					if(oEvent.keyCode==37 || oEvent.keyCode==38){
						speed =-10;
					}else if(oEvent.keyCode==39 || oEvent.keyCode==40){
						speed =10;
					}
					if(oEvent.keyCode==38 || oEvent.keyCode==40){
						odiv.style.top=odiv.offsetTop+speed+'px';
					}
					if(oEvent.keyCode==37 || oEvent.keyCode==39){
						odiv.style.left=odiv.offsetLeft+speed+'px';
					}	
					if(width<odiv.offsetLeft){
							odiv.style.left=width+'px';
					}else if(0>=odiv.offsetLeft){
						odiv.style.left=0+'px';
					}
					if(height<=odiv.offsetTop){
						odiv.style.top=height+'px';
					}else if(0>=odiv.offsetTop){
						odiv.style.top=0+'px';
					}
					
					
				}
			}
		</script>
	</head>
	<body>
		<div class="bj" id="contran">
			<div class="" id="odiv">
				
			</div>
		</div>
	</body>
</html>
